package com.rao.security.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * ajax请求登录成功处理器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 22:22
 */
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 参数说明：
     * @param request 请求对象
     * @param response 响应对象
     * @param auth spring security框架验证用户信息成功后的封装对象
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
            throws IOException, ServletException {
        // 登录的用户信息验证成功后执行的方法
        response.setContentType("text/json;charset=utf-8");

        Result result = new Result(0, 1000, "登录成功");

        OutputStream stream = response.getOutputStream();
        ObjectMapper om = new ObjectMapper();
        om.writeValue(stream, result);
        stream.flush();
        stream.close();
    }

}
